android内部类怎样访问外部类的控件变量

t785l4y 发布于 2013/04/02 21:23
阅读 1K+
收藏 1

@罗升阳 你好,想跟你请教个问题:

@邓凡平 你好,想跟你请教个问题:

请问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();

问号处如何设置,才能不出错?设置成test2.this程序出错

*/

}
}
}
public void sendMsg(String msg) {
try {
writer.println(msg);
} catch (Exception e) {
System.out.println(e);
}



}
}


加载中
0
fneg
fneg
看了一下,不能直接在线程里面错做UI,要使用Handler
fneg
fneg
回复 @t785l4y : 都是从菜鸟开始
t
t785l4y
谢啦,我是刚学android的菜鸟,很多东西都不懂
返回顶部
顶部