Example:
package com.AndroidStack;
import java.util.Stack;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidStackActivity extends Activity {
EditText input;
TextView content;
Button push, pop;
Stack<String> myStack;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
input = (EditText)findViewById(R.id.input);
content = (TextView)findViewById(R.id.content);
push = (Button)findViewById(R.id.push);
pop = (Button)findViewById(R.id.pop);
myStack = new Stack<String>();
ShowContent();
push.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String pushItem = input.getText().toString();
myStack.push(pushItem);
Toast.makeText(AndroidStackActivity.this,
"push: " + pushItem,
Toast.LENGTH_LONG).show();
ShowContent();
}});
pop.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(myStack.empty()){
Toast.makeText(AndroidStackActivity.this,
"Empty!",
Toast.LENGTH_LONG).show();
}else{
String popItem = myStack.pop();
Toast.makeText(AndroidStackActivity.this,
"pop: " + popItem,
Toast.LENGTH_LONG).show();
}
ShowContent();
}});
}
void ShowContent(){
if(myStack.empty()){
content.setText("- Empty -");
}else{
String lastContent = "last content: " + myStack.peek();
content.setText(lastContent);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText
android:id="@+id/input"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/push"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="push" />
<Button
android:id="@+id/pop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="pop" />
<TextView
android:id="@+id/content"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
0 Response to "java.util.Stack"
Posting Komentar