رفتن به مطلب
انجمن اندروید ایران | آموزش برنامه نویسی اندروید و موبایل
  • android.png.1fab383bc8500cd93127cebc65b1dcab.png

آموزش : نحوه ی ایجاد کامپوننت های سفارشی در اندروید


پست های پیشنهاد شده

ضمن عرض سلام و احترام خدمت تمامی کاربران فروم محبوب انجمن اندروید ایران
، همانطور که قول دادم بهتون ،قصد دارم یکسری مقالات در زمینه برنامه نویسی های مختلف ، برای شما عزیزان قرار دهم . پیشاپیش از تمامی مدیران فروم قدردانی میکنم بابت این فروم بسیار مفید و کاربردی.

در این مقاله می پردازیم به مبحثی کاربردی تحت عنوان :نحوه ی ایجاد کامپوننت های سفارشی در اندروید

 

اندروید لیست بزرگی از ویجت های از پیش ساخته شده مانند Button، TextView، EditText، ListView، CheckBox، RadioButton، Gallery، Spinner، AutoCompleteTextView و غیره را ارائه می کند،که شما میتوانید مستقیما در اپلیکیشن خود از آن ها استفاده کنید.

ولی ممکن است موقعیتی به وجود بیاید که شما از قابلیت های ویجت های موجود راضی نباشید به طوری که حس کنید این ویجت ها نیاز و خواسته ی شما را برطرف نمی کند. اندروید ابزار هایی را برای سفارشی سازی این موارد فراهم کرده است که با کمک آن ها می توانید با توجه به نیاز خود ، عمل سفارشی سازی را انجام دهید.

اگر فقط نیازمند اعمال تغییرات و تنظیمات کوچکی در یک ویجت یا Layout موجود باشید، می توانید به سادگی یک زیر کلاس از ویجت یا Layout مربوطه ایجاد کنید و متد های آن را override کنید. این کار به شما کنترل دقیقی را ، بر روی ظاهر و عملکرد یک عنصر موجود بر روی صفحه نمایش ، می دهد .

این مقاله با استفاده از گام ها و مراحل ساده شرح می دهد که شما چگونه می توانید view های سفارشی خود را ایجاد کنید و آن ها را در اپلیکیشن خود به کار بگیرید .

 

ایجاد یک مولفه سفارشی ساده:

در صورتی که شما بخواهید عملکرد یک ویجت موجود مانند Button، TextView، EditText، ListView، CheckBox و غیره را توسعه دهید، ساده ترین راه برای ایجاد مولفه­ ی سفارشی مربوط به خودتان، توسعه کلاس مربوط به ویجت موجود یا زیر کلاس های مربوط به کلاس خودتان است. در غیر این صورت شما باید با شروع از کلاس android.view.View همه کارها را خودتان انجام دهید.

در ساده ترین شکل، شما باید سازنده (constructors) های خود را متناظر با همه سازنده های کلاس اصلی بنویسید. 

1) یگ پروژه جدید در اندروید استودیو ایجاد کنید و آن را با نام myapplication تحت پکیج com.example.clicksite7.myapplication ایجاد کنید.

2) فایل XML به صورت res/values/attrs.xml برای تعریف اتریبیوت های جدید به همراه نوع داده آنها ، تعریف کنید .

3) فایل src/mainactivity.java را برای اضافه کردن کدها ، جهت تعریف اجزای سفارشی ، ایجاد کنید .

4) فایل res/layout/activity_main.xml را تغییر دهید و کدهای لازم را اضافه کنید.(مطابق کدهای زیر)

5) اپلیکیشن را اجرا کنید و نتیجه را در امولاتور مورد بررسی قرار دهید .

 

فایل اتریبیوت زیر را با نام attrs.xml در پوشه res/values ایجاد کنید :

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="TimeView">
      <declare-styleable name="TimeView">
         <attr name="title" format="string" />
         <attr name="setColor" format="boolean"/>
      </declare-styleable>
   </declare-styleable>
</resources>

 

فایل layout استفاده شده توسط اکتیویتی را تغییر دهید :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   xmlns:custom="http://schemas.android.com/apk/res-auto"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity" >

   <com.example.clicksite7.myapplication.TimeView
      android:id="@+id/timeView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:textColor="#fff"
      android:textSize="40sp"
      custom:title="my time view"
      custom:setColor="true" />

   <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:id="@+id/simple"
      android:layout_below="@id/timeView"
      android:layout_marginTop="10dp" />
</RelativeLayout>

 

فایل جاوای زیر را با نام timeview ایجاد کنید  :

package com.example.clicksite7.myapplication;
/**
 * Created by clicksite7 on 9/14/2016.
 */
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Context;
import android.content.res.TypedArray;

import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.TextView;

public class TimeView extends TextView {
   private String titleText;
   private boolean color;

   public TimeView(Context context) {
      super(context);
      setTimeView();
   }

   public TimeView(Context context, AttributeSet attrs) {
      super(context, attrs);
      // retrieved values correspond to the positions of the attributes
         TypedArray typedArray = context.obtainStyledAttributes(attrs, 
            R.styleable.TimeView);
      int count = typedArray.getIndexCount();
      try{
         
         for (int i = 0; i < count; ++i) {
            
            int attr = typedArray.getIndex(i);
            // the attr corresponds to the title attribute
            if(attr == R.styleable.TimeView_title) {
               
               // set the text from the layout
               titleText = typedArray.getString(attr);
               setTimeView();
            } else if(attr == R.styleable.TimeView_setColor) {
               // set the color of the attr "setColor"
               color = typedArray.getBoolean(attr, false);
               decorateText();
            }
         }
      }
        
      // the recycle() will be executed obligatorily
      finally {
         // for reuse
         typedArray.recycle();
      }
   }

   public TimeView(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
      setTimeView();
   }

   private void setTimeView() {
      // has the format hour.minuits am/pm
      SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm aa");
      String time = dateFormat.format(Calendar.getInstance().getTime());
      
      if(this.titleText != null )
      setText(this.titleText+" "+time);
      else
         setText(time);
   }

   private void decorateText() {
      // when we set setColor attribute to true in the XML layout
      if(this.color == true){
         // set the characteristics and the color of the shadow
         setShadowLayer(4, 2, 2, Color.rgb(250, 00, 250));
         setBackgroundColor(Color.CYAN);
      } else {
         setBackgroundColor(Color.RED);
      }
   }
}

فایل اصلی اکتیویتی جاوا را به کد زیر تغییر دهید و اپلیکیشن خود را اجرا کنید :

package com.example.clicksite7.myapplication;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      TextView simpleText = (TextView) findViewById(R.id.simple);
      simpleText.setText("That is a simple TextView");
   }
}

 

لینک ارسال
به اشتراک گذاری در سایت های دیگر

به گفتگو بپیوندید

هم اکنون می توانید مطلب خود را ارسال نمایید و بعداً ثبت نام کنید. اگر حساب کاربری دارید، برای ارسال با حساب کاربری خود اکنون وارد شوید .

مهمان
ارسال پاسخ به این موضوع...

×   شما در حال چسباندن محتوایی با قالب بندی هستید.   حذف قالب بندی

  تنها استفاده از 75 اموجی مجاز می باشد.

×   لینک شما به صورت اتوماتیک جای گذاری شد.   نمایش به صورت لینک

×   محتوای قبلی شما بازگردانی شد.   پاک کردن محتوای ویرایشگر

×   شما مستقیما نمی توانید تصویر خود را قرار دهید. یا آن را اینجا بارگذاری کنید یا از یک URL قرار دهید.

  • مطالب مشابه

    • توسط 3245
      سلام
      من درحال اموزش اندروید هستم،
      برای این کار، ویدیوهای ساخت کتاب رو خریدم، اما چون اطلاعاتم خیلی کمه،درک مطالب توی این ویدئو سخته برام
      میخواستم اگرممکنه دوستان کلیپی پیشنهاد بدن که سبک تر باشه و بیشتر به مباحث پایه بپردازه، البته خیلی هم نخواد از صفر شروع کنه که خسته کننده میشه...
      طوری باشه پروژه محور باشه اما پروژه سبکی باشه.
       
      ممنون.
       
       
    • توسط aliazmoodeh
      سلام من یه آپی دارم یه قسمت وجود داره که اطلاعات رو از سرور میگیره و تو ریسایکلرویو نمایش میده من میخوام این اطلاعات رو تو حالت افلاین هم داشته باشم یعنی چی یعنی بتونم اطلاعاتی که از سرور گرفتم قبلا رو وقتی کاربر اینترنت بهش نمایش بدم دقیقن مثله تلگرام میگم ولی نمیدونم باید چیکار کنم اگر اموزشی در این رابط دارید بهم بگید یا سورسی دارید بهم بگید پولی یا رایگان باشه برام فرقی نمیکنه فقط میخوام مشکلمو حل کنه
    • توسط Zeynab Tri
      سلام. دوستان بنده یک عدد تازه کار در برنامه نویسی اندروید هستم و نمیدونم این ارور رو چطور حل کنم. ممنون میشم اگر کسی میتونه من رو راهنمایی کنه.عکسش رو گذاشتم.

    • توسط moein123
      سلام دوستان خوبین؟
      من برای آپ خودم ثبتنام و لاگین دارم میسازم
      ثبتنام کاربر به خوبی کار میکنه و مشکلی نداره
      ولی برای لاگین کردن نمیدونم چرا کار نمیکنه
      پیغام خطا هم نمیده
      ببینین این کد سمت سروری که نوشتم
      <?php if($_SERVER['REQUEST_METHOD']=='POST'){ $mail2=$_POST['mail']; $password=$_POST['pass']; require_once 'connect.php'; $sql = "SELECT * FROM register WHERE mail='$mail2' "; $response=mysqli_query($conn,$sql); $result=array(); $result['login']=array(); if(mysqli_num_rows($response)===1){ $row=mysqli_fetch_assoc($response); if(password_verify($password,$row['pass'])){ $index['name']=$row['name']; $index['mail']=$row['mail']; array_push($result['login'],$index); $result['okk']='1'; $result['message']='okk'; echo json_encode($result); mysqli_close($conn); }else{ $result['okk']='0'; $result['message']='error'; echo json_encode($result); mysqli_close($conn); } } } ?> و اینم کد های جاوای اندروید که نوشتم
      package com.android.register1; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.print.PageRange; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.android.material.snackbar.Snackbar; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class loginn extends AppCompatActivity { EditText edt_username,edt_password_login; Button btn_login; ProgressBar my_progcess; static String url_login="http://192.168.1.103/register2/login.php"; LinearLayout my_manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loginn); find_all(); } private void find_all() { edt_username=findViewById(R.id.edt_username); edt_password_login=findViewById(R.id.edt_pass_login); my_progcess=findViewById(R.id.my_progcess_login); btn_login=findViewById(R.id.btn_login); my_manager=findViewById(R.id.my_manager); btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String musername=edt_username.getText().toString().trim(); String mpassword=edt_password_login.getText().toString().trim(); if(!musername.isEmpty() || !mpassword.isEmpty()){ my_login(musername,mpassword); }else { edt_username.setError("username"); edt_password_login.setError("password"); } } }); } public void my_login(final String mail,final String pass){ my_progcess.setVisibility(View.VISIBLE); btn_login.setVisibility(View.GONE); StringRequest request=new StringRequest(Request.Method.POST, url_login, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject=new JSONObject(response); String message=jsonObject.getString("okk"); JSONArray jsonArray=jsonObject.getJSONArray("login"); if(message.equals("1")){ for (int i = 0; i <jsonArray.length() ; i++) { JSONObject jsonObject1=jsonArray.getJSONObject(i); String name=jsonObject1.getString("name").trim(); String mail=jsonObject1.getString("mail").trim(); Snackbar snackbar=Snackbar.make(my_manager, name+mail+"لاگین شدید",Snackbar.LENGTH_LONG); snackbar.getView().setTranslationY(-100); snackbar.show(); } } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(loginn.this, "error1"+e.toString(), Toast.LENGTH_SHORT).show(); my_progcess.setVisibility(View.GONE); btn_login.setVisibility(View.VISIBLE); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(loginn.this, "error2"+error.toString(), Toast.LENGTH_SHORT).show(); my_progcess.setVisibility(View.GONE); btn_login.setVisibility(View.VISIBLE); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String,String>params=new HashMap<>(); params.put("mail",mail); params.put("pass",pass); return params; } }; RequestQueue requestQueue= Volley.newRequestQueue(this); requestQueue.add(request); } } ممنون میشم کمکم کنید 
    • توسط hossein1212
      سلام 
      من در اجرا شبیه ساز به مشکل زیر خورده ام راه حلی داره
      اینترنتم اوکیه ولی دانلود نمیکنه


  • فایل

×
×
  • اضافه کردن...