【发布时间】:2019-05-10 18:10:47
【问题描述】:
我是 Android 编程新手。我有一个 Main Activity,它实现了一些 TextView 和 custom-view 的布局。布局是这样的:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/turnTextView"
//and other tags
/>
<com.example.crosstheboxprova.GameMap
android:id="@+id/gameMapView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="0dp"
android:layout_marginEnd="0dp"
android:layout_marginRight="0dp"
android:layout_marginBottom="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/turnTextView" />
</android.support.constraint.ConstraintLayout>
custom-view 是这样的:
public class GameMap extends View {
private TextView tv;
public GameMap(Context context) {
super(context);
init(context);
}
public GameMap(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public GameMap(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public GameMap(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
private void init(Context context){
//do I have to use the context in some way?
//here or on other part of the class I need something like:
tv = findViewById(R.id.turnTextView); //returns null
tv.setText("hello");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/***/
}
@Override
public boolean onTouchEvent(MotionEvent event) {
}
}
MainActivity 是这样的:
public class MainActivity extends AppCompatActivity {
private GameMap gameMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
gameMap = new GameMap(this);
}
}
问题是,当我调用FindViewById() 访问TextView 并从custom-view 内部设置文本时,它返回null 并抛出NullPonterException。如何从custom-view 内部访问TextView?
【问题讨论】:
-
您似乎没有在自定义视图中的任何位置引用您的布局文件
-
哦。我明白了,TextView 在布局文件之外。您将无法获得对不在自定义视图自己的布局内的小部件的引用。您可能需要考虑使用某种回调机制从您的自定义视图中获取输出。
-
@IvanWooll 你能给我看一个你的答案的例子吗?正如我所说的,我对此很陌生。
标签: android android-custom-view findviewbyid