关于网友提出的“android内部类怎样访问外部类的控件变量”问题疑问,本网通过在网上对“android内部类怎样访问外部类的控件变量”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题:android内部类怎样访问外部类的控件变量
描述: @邓凡平 你好,想跟你请教个问题:
请问android内部类怎样访问外部类的控件变量(TextView),如字符变量就可以,但设置外部类的控件变量就出错。代码实现的功能是连接到服务器端,服务器发送过来信息,就自动显示在文本区内。
代码如下:(主要看粗体字)
public class test2 extends Activity
{
private static final String SERVERIP = "10.0.2.2";
private static final int SERVERPORT = 6501;
TextView mMsgRev;
EditText mMsgEdit;
Button mMsgSendBtn;
Button show;
String mSendMsg;
String mReceivedMsg="";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.a);
mMsgRev = (TextView) findViewById(R.id.receive_msg);
mMsgEdit = (EditText) findViewById(R.id.edit_msg);
mMsgSendBtn = (Button) findViewById(R.id.send_msg);
show=(Button)findViewById(R.id.show);
mMsgSendBtn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//Socket socket = null;
mSendMsg = mMsgEdit.getText().toString();
new client(SERVERIP, SERVERPORT).start();
}
});
show.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(test2.this, mReceivedMsg, Toast.LENGTH_LONG).show();
}
});
}
class client extends Thread //内部类
{
Socket sc;
BufferedReader reader;
PrintWriter writer;
public client(String ip, int port)
{
try
{
sc = new Socket(ip, port);
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sc.getOutputStream())));
reader = new BufferedReader(new InputStreamReader(sc.getInputStream()));
} catch (Exception e)
{
// TODO: handle exception
System.out.println(e);
}
}
public void run()
{
String msg = "";
while (true)
{
try
{
msg=reader.readLine();
} catch (Exception e)
{
// TODO: handle exception
System.out.println(e);
}
if (msg!=null&&msg.trim()!= "")
{
mReceivedMsg=msg; //外部类的普通变量可以设置,没有出错
mMsgRev.setText(mReceivedMsg);//外部类的控件变量设置就会出错
/*
Toast.makeText(??, msg, Toast.LENGTH_LONG).show();
问号处如何设置,才能不出错?
*/
}
}
}
public void sendMsg(String msg) {
try {
writer.println(msg);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
以上介绍了“android内部类怎样访问外部类的控件变量”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/1279746.html