我正在尝试将我的活动中的String变量传递给我自定义创建的视图类。我已经尝试过Bundle但它似乎不起作用。我想将我的MainActivity中名为'destination'的EditText的输入值传递给我的DrawView类。我想要实现的是取决于活动类中的用户输入,DrawView类将在不同的位置绘制形状任何帮助将不胜感激。
这是我的活动类的代码
MainActivity.class
public class MainActivity extends ActionBarActivity {
static EditText destination = (EditText)findViewById(R.id.roomdinput);
String roomName;
//DrawView drawView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button floorPlan = (Button)findViewById(R.id.floorPlanButton);
floorPlan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
roomName = destination.getText().toString();
Bundle myb = new Bundle();
myb.putString("key", roomName);
Intent a = new Intent(MainActivity.this, DrawView.class);
a.putExtras(myb);
startActivity(a);
startActivity(new Intent("com.example.helloworld3.FLOORPLAN"));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
这是我的DrawView类的代码
DraView.class
public class DrawView extends View {
Paint paint = new Paint();
float ux, dx, rx,lx;
String roomName2;
Bundle myb2 ;
public DrawView(Context context) {
super(context);
paint.setColor(Color.RED);
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawLine(90, 250 , 90, 400, paint);
canvas.drawLine(20, 0, 0, 20, paint);
canvas.drawCircle(150, 400, 30, paint);
}
}
答案 0 :(得分:2)
就DrawView
扩展View
而言,您可以使用setTag
方法将对象传递给视图。为什么不使用这个有用的功能?
SomeCustomObject obj = new SomeCustomObject();
myDrawView.setTag(obj);
在视图中,您可以使用getTag
方法获取标记。
SomeCustomObject = (SomeCustomObject)getTag();
当然,您可以在DrawView
类
喜欢
public class DrawView extends View {
SomeCustomObject obj ;
Paint paint = new Paint();
float ux, dx, rx,lx;
String roomName2;
Bundle myb2 ;
// Custom constructor
public DrawView(Context context,SomeCustomObject object) {
this(context);
this.obj = object;
}
// Custom method
public void setObject(SomeCustomObject object) {
this.obj = object;
}
public DrawView(Context context) {
super(context);
paint.setColor(Color.RED);
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawLine(90, 250 , 90, 400, paint);
canvas.drawLine(20, 0, 0, 20, paint);
canvas.drawCircle(150, 400, 30, paint);
}
}
如果你的DrawView
在另一个活动中并且你想要传递数据,首先你应该通过Intent传递它,而不是在第二个活动中从intent获取对象,然后将此对象传递给你的{ {1}}。如果你需要一个例子,那就说吧。
答案 1 :(得分:0)
只需调用view object和setContentView
即可drawView = new DrawView(this);
setContentView(drawView);
此外,如果您希望在parameters
setter
传递创建View
方法