Я довольно новичок в программировании на Android в целом, и у меня возникли особые трудности с перемешиванием пользовательского интерфейса xml / java ... У меня есть макет, который я хотел бы использовать в качестве представления, отображаемого при создании экземпляра пользовательского класса представления в класс деятельности. Это прекрасно работает, просто позвонив
setContentView(R.layout.mylayout) ;
в действии или из пользовательского класса представления через дескриптор к действию. Проблема возникает, когда я хочу взаимодействовать с виджетами на макете - я попытался получить ручку на кнопках с
myButton = (Button) findViewById(R.id.mybuttonid);
и отдельно с
Button myButton = new Button(contextHandle);
myButton = (Button) findViewById(R.layout.mybuttonid);
но в обоих случаях всякий раз, когда я пытаюсь вызвать какие-либо методы из предполагаемого объекта myButton, я получаю исключение NullPointerException в отчете logcat; очевидно, что myButton не создан должным образом ни в одном из приведенных выше случаев. Как правильно создать экземпляры компонентов представления в подобном случае, который объединяет XML и Java, чтобы они могли динамически вызывать методы?
спасибо,
CCJ
РЕДАКТИРОВАТЬ: Спасибо всем за ответы, но я думаю, что до 01.08.2011 совет был в основном ориентирован на реализацию, где виджеты должны быть созданы в классе деятельности; Я хочу создать экземпляры виджетов из макета xml в пользовательском классе представления - классе, полностью отделенном от класса действия, который расширяет View и реализует собственный интерфейс OnClickListener. Ниже мой код:
Класс MyActivity:
package com.ccg.myactivity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
public class MyActivity extends Activity implements OnClickListener {
private boolean touched = false;
private RadioButton myRB;
private Button runB;
private CustomView myView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlayout);
myRB = (RadioButton) findViewById(R.id.testrb);
runB = (Button) findViewById(R.id.goButton);
//set onClick listeners for activity class
runB.setOnClickListener(this);
}
public void onResume(){
super.onResume();
}
public void onClick(View v) {
// do something when the button is clicked
if (myRB.isChecked()){
setContentView(R.layout.mylayout);
myView = new CustomView(this,this); //passing in activity and context
//handles to custom View class
//myView.getAnotherB().setOnClickListener(this); //commented out as we
//don't want to register the custom view's button with the Activty class's
//OnClickListener; instead it should be registered with the custom View class's own
//OnClickListener implementation.
}
else{
Log.d("me","alt click");
}
}
}
Класс CustomView:
package com.ccg.myactivity;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.view.View.OnClickListener;
public class CustomView extends View implements OnClickListener{
private Button anotherB;
private Context contextHandle;
private Activity actHandle;
public CustomView(Context context, Activity act) {
super(context);
contextHandle = context;
actHandle = act;
//anotherB = new Button(contextHandle); //this shouldn't be necessary for
//instantiation from XML widget
initCustomView();
}
public void initCustomView(){
anotherB = (Button) findViewById(R.id.nextbutton);
anotherB.setOnClickListener(this);
}
public Button getAnotherB(){
return anotherB;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("me", "Got the custom click!");
}
}
mainlayout.xml, из которого сделан вид по умолчанию:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/widget474"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<RadioGroup android:id="@+id/widget30" android:orientation="horizontal"
android:layout_x="2dip" android:layout_y="57dip" android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton android:layout_height="wrap_content" android:id="@+id/testrb"
android:textSize="15sp" android:text="Run" android:layout_width="wrap_content"
android:textColor="#ffff99ff"></RadioButton>
</RadioGroup>
<Button android:layout_width="wrap_content" android:text="@string/RUN"
android:id="@+id/goButton" android:layout_height="wrap_content"
android:layout_x="222dip" android:layout_y="110dip"></Button>
</LinearLayout>
mylayout.xml, из которого создается макет пользовательского представления:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<Button android:id="@+id/nextbutton" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="work!!!"
>
</Button>
</LinearLayout>
хорошо, если кто-нибудь может объяснить, почему какой-либо метод вызывает из объекта кнопки anotherB (anotherB.setOnClickListener (this) выше), но также и более простой anotherB.bringToFront ()), вызывающий принудительное закрытие и исключение nullpointerexception в logcat с вышеуказанной реализацией Я был бы очень признателен. Спасибо!
CCJ