Пример кода, расширяющего класс View и использующего XML-файл layout

#android #android-custom-view

#Android #android-пользовательский вид

Вопрос:

Я новичок в мире Android …. это будет большим подспорьем, если кто-нибудь меня поправит… что я делаю не так в приведенном ниже коде…

  • Требование: Необходимо создать пользовательский вид (используя xml-файл layout), чтобы тот же вид использовался внутри в моих действиях приложения. Здесь я перехожу к образцу кода, над которым я работаю,

cutomviewxml.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@ id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
  

Расширенный класс View …code…

mycustomTextview.java

 public class mycustomTextview extends View {

    private View mView;
    Context mycontext;

    public mycustomTextview(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub

    this.mycontext = context;

    LayoutInflater inflater;
    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mView = inflater.inflate(R.layout.cutomviewxml, null);
    }
  

Активность main.xml файл

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


     <com.motorola.mycustomTextview
         android:id="@ id/customtextview"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_below="@ id/textView2"
         android:layout_marginLeft="143dp"
         android:layout_marginTop="69dp"
         android:layout_toRightOf="@ id/textView1" />

</RelativeLayout>
  

Класс Activitysample.java ..

 public class sample extends Activity{

    private static final String LOG_TAG = "sampleActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(LOG_TAG,"OnCreate of sampleActivity");
        setContentView(R.layout.main);
}
}
  

Ответ №1:

Я думаю, вы допустили небольшую ошибку в mycustomTextview , когда вы раздуваете свой макет, вам также приходится передавать ViewGroup, вы можете использовать эту строку

 mView = inflater.inflate(R.layout.cutomviewxml, this);
  

Ответ №2:

Чтобы получить доступ к представлениям внутри пользовательского представления, переопределите метод onFinishInflate() и используйте findViewById(). Для рассматриваемой проблемы решение будет следующим.

 public class mycustomTextview extends LinearLayout {

    Context mycontext;
    private TextView textView1;

    public mycustomTextview(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mycontext = context;
    }

    @Override
    protected void onFinishInflate() {
         super.onFinishInflate();
         textView1=(TextView) findViewById(R.id.textView1);
    }
}
  

Комментарии:

1. Как можно передать параметры этому классу mycustomTextview, если мне нужно?

Ответ №3:

Используйте это в своем xml:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
        <yourpackagename.viewclassname android:id="@ id/myView1" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content"></yourpackagename.viewclassname>
</LinearLayout>
  

Ответ №4:

 public class ExampleView extends FrameLayout {

        ImageView mImage;

        public ExampleView(Context context) {
            super(context);
            init(context);
        }

        public void init(Context context) {
            View view = inflate(context, R.layout.my_view_layout,this);
            view.findViewById(R.id.image)
        }
}