I am using SeekBar to change the opacity level in drawing But I am getting Nullpointer exception in the lines
seekOpq.setMax(100);
and
seekTxt.setText(currLevel);
in the following code..
public void onClick(View view){
if(view.getId()==R.id.opacity_btn){
//launch opacity chooser
final Dialog seekDialog = new Dialog(this);
final TextView seekTxt = (TextView)seekDialog.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar)seekDialog.findViewById(R.id.seek);
Toast.makeText(getApplicationContext(),
"start.", Toast.LENGTH_SHORT).show();
seekDialog.setTitle("Opacity level:");
seekDialog.setContentView(R.layout.opacity_chooser);
seekOpq.setMax(100);
int currLevel = drawView.getPaintAlpha();
seekTxt.setText(currLevel);
seekOpq.setProgress(currLevel);
seekOpq.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
seekTxt.setText(Integer.toString(progress)+" % ");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar){}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
Button opqBtn = (Button)seekDialog.findViewById(R.id.opq_ok);
opqBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
drawView.setPaintAlpha(seekOpq.getProgress());
Toast.makeText(getApplicationContext(),
"end.", Toast.LENGTH_SHORT).show();
seekDialog.dismiss();
}
});
}
I have tried giving numeric arguments manualy to these lines like
seekTxt.setText(50);
But the error still remains the same
This is my opacity_chooser.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/opq_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="100%"
android:textStyle="bold" />
<SeekBar
android:id="#+id/seek"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
<Button
android:id="#+id/opq_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
First set Content View after initialize seekbar & textview.
eg.
final Dialog seekDialog = new Dialog(this);
seekDialog.setContentView(R.layout.opacity_chooser);
final TextView seekTxt = (TextView)seekDialog.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar)seekDialog.findViewById(R.id.seek);
Toast.makeText(getApplicationContext(),
"start.", Toast.LENGTH_SHORT).show();
seekDialog.setTitle("Opacity level:");
seekOpq.setMax(100);
-------------------
Related
I am having troubles setting the two buttons on the lower part of the alert what I am trying to do is get a similar look to the IOS look of the buttons.
here is my current code:
public void openInstructions() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
setNewDateOnView();
dialog.cancel();
}
}).setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).create();
TextView myMsg = new TextView(getActivity());
myMsg.setText("ExampleText ");
myMsg.setTextSize(15);
myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
dialog.setView(myMsg);
dialog.setTitle("Confirm Date of Purchase");
dialog.setOnShowListener( new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface arg0) {
Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
negativeButton.setTextColor(0xFFFF0000);
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setTextColor(0xFF0000FF);
}
});
dialog.show();
}
Example of how it looks right now:
How I wanted it to look:
To design Dialog like ios , we can create custom dialog using custom layout like this :
dialog_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="vertical"
app:layout_constraintHeight_max="wrap">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/custom_bg">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="#+id/title"
android:gravity="center"
android:text="Confirm Date of Purchase"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="17sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/back_ll"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/rebooking_single_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textAlignment="center"
android:text="#string/dummuy"
android:textColor="#android:color/black"
android:textSize="17sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/back_ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/end_time_recycle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#8F8F8F" />
<LinearLayout
android:id="#+id/rebooking_back_button_ll"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/ok_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".49"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Ok"
android:textAlignment="center"
android:textColor="#FF6363"
android:textSize="17sp"
android:textStyle="bold" />
<View
android:layout_width="0dp"
android:layout_weight=".01"
android:layout_height="match_parent"
android:layout_below="#+id/end_time_recycle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#8F8F8F" />
<TextView
android:id="#+id/cancel_btn"
android:layout_width="0dp"
android:layout_weight=".5"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAlignment="center"
android:paddingRight="10dp"
android:text="Cancle"
android:textColor="#7BC5FF"
android:textSize="17sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Main_Activity
final Dialog dialog=new Dialog(FirstActivity.this);
dialog.setCancelable(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_custom);
TextView cancel_btn=dialog.findViewById(R.id.cancel_btn);
cancel_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
dialog.dismiss();
}
});
TextView ok_btn=dialog.findViewById(R.id.ok_btn);
ok_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
dialog.dismiss();
}
});
dialog.show();
Well, as a start, google recommends you use the Android Design Guidelines when creating Android apps, really you should be sticking to those as that's what your users will be used to (not Apple's).
Also there's no reason to be assigning the dialog a TextView if all you're doing is showing text, the AlertDialog provides this functionality with setMessage.
If that hasn't convinced you to stick to the normal design rules, the only other option would be creating a Custom View and assign it to the AlertDialog with setView(similar to how you're doing it with the TextView).
Here's a tutorial on creating a Custom View
You can create a custom view such as the one sent and inflate it
Example:
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
View mView=getActivity().getLayoutInflater().inflate(R.layout.custom_layout, null);
mBuilder.setView(mView);
Button close = (Button) mView.findViewById(R.id.close);
Button OK = (Button) mView.findViewById(R.id.ok);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//close the dialog
hideDialog1();
}
});
OK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
Use .setNeutralButton that make place left most
TextView textview;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button =(Button)findViewById(R.id.button1);
textview = (TextView)findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_launcher_background)
.setTitle("Alert Dialog Box Title")
.setMessage("Are you sure( Alert Dialog Message )")
.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on Yes", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on Cancel", Toast.LENGTH_SHORT).show();
}
})
.setNeutralButton("NO", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on NO", Toast.LENGTH_SHORT).show();
}
})
.show();
}
});
}
===============================================
public class MainActivity extends AppCompatActivity {
MaterialEditText edtNewUser, edtNewPassword, edtNewEmail; //pentru Sign up
MaterialEditText edtUser, edtPassword, edtEmail; //pentru Sign in
Button btnSignUp, btnSignIn;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Firebase
database = FirebaseDatabase.getInstance();
users = database.getReference("Users");
edtUser = (MaterialEditText)findViewById(R.id.edtUser);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
btnSignIn = (Button)findViewById(R.id.btn_sign_in);
btnSignUp = (Button)findViewById(R.id.btn_sign_up);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showSignUpDialog();
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn(edtUser.getText().toString(), edtPassword.getText().toString());
}
});
}
private void signIn(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user).exists()){
if(!user.isEmpty()){
User login = dataSnapshot.child(user).getValue(User.class);
if(login.getPassword().equals(pwd))
Toast.makeText(MainActivity.this, "Login ok!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Parola incorecta!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Va rog introduceti username!", Toast.LENGTH_SHORT).show();
}
}
else
Toast.makeText(MainActivity.this, "Username-ul nu exista!", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showSignUpDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Sign up");
alertDialog.setMessage("Introduceti informatiile necesare");
LayoutInflater inflater = this.getLayoutInflater();
View sign_up_layout = inflater.inflate(R.layout.sign_up_layout,null);
edtNewUser = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewUserName);
edtNewEmail = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewEmail);
edtNewPassword = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewPassword);
alertDialog.setView(sign_up_layout);
alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final User user = new User(edtNewUser.getText().toString(),
edtNewPassword.getText().toString(),
edtNewEmail.getText().toString());
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user.getUserName()).exists())
Toast.makeText(MainActivity.this, "User-ul exista deja!",Toast.LENGTH_SHORT).show();
else{
users.child(user.getUserName()).setValue(user);
Toast.makeText(MainActivity.this, "Inregistrat cu success!",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
XML file
<?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"
android:background="#color/colorPrimary"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/info_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardElevation="4dp"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtNewUserName"
android:hint="Username"
android:textColorHint="#color/colorPrimary"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:met_baseColor="#color/colorPrimary"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtNewPassword"
android:hint="Password"
android:textColorHint="#color/colorPrimary"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:met_baseColor="#color/colorPrimary"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
<LinearLayout
android:layout_below="#id/info_login"
android:orientation="horizontal"
android:weightSum="2"
android:layout_margin="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#id/btn_sign_up"
android:text="Sign up"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="#id/btn_sign_in"
android:text="Sign in"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Please help me! I've tried anything I knew but nothing works
The program I work in is ANDROID STUDIO. I need to solve this to finish my app.
signIn(edtUser.getText().toString(), edtPassword.getText().toString());
This is the line that gives me ERROR. If I comment this line the app works properly but I need it for the rest of the app.
Your edtUser MaterialEditText and edtPassword are not present in your xml file, you have to change the ids in xml file to match the Activity ids, or remplace
edtUser = (MaterialEditText)findViewById(R.id.edtUser);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
by :
edtUser = (MaterialEditText)findViewById(R.id.edtNewUserName);
edtPassword = (MaterialEditText)findViewById(R.id.edtNewPassword);
I'm new to Android development so please bear with me.
I have the code inside an activity that implements qr scanning. Basically there is an activity before this segments of codes, but its just clicking of a button to go here. and whenever I do that, my app crashes and that is the error that returns. The idea of the app is once the user click the button, it will first display a qr scanner, once it has been scanned, it will now call this XML File
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_scan"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/scanbg"
tools:context=".ScanActivity">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:layout_marginTop="62dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question Here"
android:textSize="22dp"
android:id="#+id/questionhere"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/questionhere"
android:hint="Answer"
android:id="#+id/answerhere"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Correct or not indicator"
android:id="#+id/indicator"
android:layout_below="#id/answerhere"
android:textSize="18dp"/>
<!--this textview will be programmed to be changed as correct or not-->
<!--if answer == correct then "correct!" else "wrong answer"-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Point(s):"
android:id="#+id/userpoints"
android:layout_below="#id/indicator"
android:textSize="18dp"/>
<Button
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/userpoints"
android:layout_alignParentEnd="true"
android:text="Go"
android:textSize="14dp"
android:background="#B0DAD5"
android:id="#+id/gosagot"/>
</RelativeLayout>
and Here is the java file
public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Button validateanswer;
ProgressDialog progress;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
validateanswer = (Button)findViewById(R.id.gosagot); //Im having error here
validateanswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress.setMessage("Connecting...");
progress.setCancelable(false);
progress.show();
EditText theanswer = (EditText)findViewById(R.id.answerhere);
String sagotdito = theanswer.getText().toString();
RequestFactory.confirmanswer(ScanActivity.this, sagotdito, new RequestCallback<Boolean>() {
#Override
public void onSuccess(Boolean response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
finish();
//load new question
progress.dismiss();
}
});
}
#Override
public void onFailed(String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ScanActivity.this, "Wrong Answer. Try Again!", Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
});
}
});
}
continuation...
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
Log.w("handleResult",result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText answertoQuestion = new EditText(this);
answertoQuestion.setHint("answer");
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
setContentView(R.layout.activity_scan);
TextView j = (TextView)findViewById(R.id.questionhere);
EditText k = (EditText)findViewById(R.id.answerhere);
String n = k.getText().toString();
j.setText(result.getText());
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
please help me.
If you check the examples of ZXing...
In your activity XML, you can add a region for the QR scanner.
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Grab that and add the scanner view there.
public class ScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_simple_scanner);
ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
mScannerView = new ZXingScannerView(this);
contentFrame.addView(mScannerView);
}
Your error is that you can't findViewById on your button when you replaced the content view with some other view that doesn't have the ID you want to find.
And even if you "switched" findViewById and setContentView around, your code wouldn't crash, but you would no longer have a button in the content view, so having the click action would be pointless.
The problem is that the button is a part of activity_scan and you set setContentView(mScannerView) to other layout.You are bound to get this error as the activity does not have a refernce to the view(button) you are refering.
What you can do is make the mScannerView a part of your main layout and then get it with findViewById();
I am working on an application which needs to save and restore the textview scroll position when the user changes the screen orientation and when the user quits the application, i am using multiple textViews(8-10) due to very very long text block. I took help from some answers here but they don't seem to work, and plz suggest a better way to include very very large text blocks in an activity. Code given below:
Thanks in advance,
chapter1.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollChapter1">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/Chapter1"
android:textSize="17sp"
android:padding="10px"
android:id="#+id/txtChapter1Title"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:width="0dip"
android:textSize="16sp"
android:padding="10px"
android:text="#string/Chapter1ContentA"
android:id="#+id/txtChapter1A"
android:maxLength="9000"
android:layout_below="#+id/txtChapter1Title"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dip"
android:width="0dip"
android:textSize="16sp"
android:padding="10px"
android:text="#string/Chapter1ContentB"
android:id="#+id/txtChapter1B"
android:maxLength="9000"
android:layout_below="#+id/txtChapter1A"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dip"
android:width="0dip"
android:textSize="16sp"
android:padding="10px"
android:text="#string/Chapter1ContentC"
android:id="#+id/txtChapter1C"
android:maxLength="9000"
android:layout_below="#+id/txtChapter1B"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dip"
android:width="0dip"
android:textSize="16sp"
android:padding="10px"
android:text="#string/Chapter1ContentD"
android:id="#+id/txtChapter1D"
android:maxLength="9000"
android:layout_below="#+id/txtChapter1C"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dip"
android:width="0dip"
android:textSize="16sp"
android:padding="10px"
android:text="#string/Chapter1ContentE"
android:id="#+id/txtChapter1E"
android:maxLength="9000"
android:layout_below="#+id/txtChapter1D"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dip"
android:width="0dip"
android:textSize="16sp"
android:padding="10px"
android:text="#string/Chapter1ContentF"
android:id="#+id/txtChapter1F"
android:maxLength="9000"
android:layout_below="#+id/txtChapter1E"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dip"
android:width="0dip"
android:textSize="16sp"
android:padding="10px"
android:text="#string/Chapter1ContentG"
android:id="#+id/txtChapter1G"
android:maxLength="9000"
android:layout_below="#+id/txtChapter1F"
/>
</RelativeLayout>
</ScrollView>
chapter1.java:
public class chapter1 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.chapter1);
WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
if(d.getWidth() > d.getHeight()){
Log.d("Orientation", "Landscape");
}else{
Log.d("Orientation", "Potrait");
}
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
final ScrollView scrollView = (ScrollView) findViewById(R.id.scrollChapter1);
final RelativeLayout relativeLayout = (RelativeLayout) scrollView.getChildAt(0);
final TextView textView = (TextView) relativeLayout.getChildAt(0);
final int firstVisibleLineOffset = textView.getLayout().getLineForVertical(scrollView.getScrollY());
final int firstVisibleCharacterOffset = textView.getLayout().getLineStart(firstVisibleLineOffset);
outState.putInt("ScrollViewContainerTextViewFirstVisibleCharacterOffset", firstVisibleCharacterOffset);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
final int firstVisibleCharacterOffset = savedInstanceState.getInt("ScrollViewContainerTextViewFirstVisibleCharacterOffset");
final ScrollView scrollView = (ScrollView) findViewById(R.id.scrollChapter1);
scrollView.post(new Runnable() {
#Override
public void run() {
final RelativeLayout relativeLayout = (RelativeLayout) scrollView.getChildAt(0);
final TextView textView = (TextView) relativeLayout.getChildAt(0);
final int firstVisibleLineOffset = textView.getLayout().getLineStart(firstVisibleCharacterOffset);
final int pixelOffset = textView.getLayout().getLineTop(firstVisibleLineOffset);
scrollView.scrollTo(0, pixelOffset);
}
});
}
}
You need to save the state of the component in order to restore it after rotation...
Try this :
// two static variable,
public static int scrollX = 0;
public static int scrollY = -1;
//update & save their value on onPause & onResume.
#Override
protected void onPause()
{
super.onPause();
scrollX = scrollView.getScrollX();
scrollY = scrollView.getScrollY();
}
#Override
protected void onResume() {
Util.Log("X:" + scrollX + " Y:" + scrollY);
super.onResume();
//this is important. scrollTo doesn't work in main thread.
scrollView.post(new Runnable(){
#Override
public void run()
{
scrollView.scrollTo(scrollX, scrollY);
}
});
}
For screen rotation :
//save value on onSaveInstanceState
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putIntArray("SCROLL_POSITION",
new int[]{ mScrollView.getScrollX(), mScrollView.getScrollY()});
}
//Restore them on onRestoreInstanceState
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final int[] position = savedInstanceState.getIntArray("SCROLL_POSITION");
if(position != null)
mScrollView.post(new Runnable() {
public void run() {
mScrollView.scrollTo(position[0], position[1]);
}
});
}
I'm making a simple "novelty" app that counts how many sneezes are done, it's more of a fun app that builds up experience until I do my huge project during the summer. I have two buttons, one adds a sneeze and the other clears how many sneezes there currently are. It holds the highest number of sneezes that there were previously. The problem is, the TextViews never update, they only initialize to zero. I used a Toast.makeText() to make sure that the buttons are working (they are). Any help is appreciated. Thanks
Java code:
public class MainActivity extends ActionBarActivity {
private int record_number = 0;
private int current_number = 0;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
Toast.makeText(MainActivity.this, "Button Clicked " + current_number, Toast.LENGTH_SHORT).show();
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
TextView rec_text = (TextView) findViewById(R.id.record_num);
TextView cur_text = (TextView) findViewById(R.id.current_num);
if (current_number >= record_number)
{
record_number = current_number;
}
rec_text.setText(String.valueOf(record_number));
cur_text.setText(String.valueOf(current_number));
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.michail.sneezecounter.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Sneeze Counter"
android:id="#+id/title"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Record Number of Sneezes:"
android:id="#+id/textView"
android:layout_below="#+id/title"
android:layout_centerHorizontal="true"
android:layout_marginTop="72dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one Sneeze"
android:id="#+id/addone"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="76dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Current Number of Sneezes"
android:id="#+id/clear"
android:layout_marginBottom="13dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/record_num"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:singleLine="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Current Number of Sneezes:"
android:id="#+id/currentLabel"
android:layout_centerVertical="true"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#+id/currentLabel"
android:layout_alignLeft="#+id/record_num"
android:layout_alignStart="#+id/record_num"
android:layout_marginTop="21dp"
android:id="#+id/current_num" />
</RelativeLayout>
You need to update the text of the TextViews inside the onClickListeners. In fact, all your logic for counting, clearing, and recording the record needs to be done in your onClickListeners (or methods called by them). Right now you only do it once in onCreate, then never again. You can do this in onCreate:
final TextView cur_text = (TextView) findViewById(R.id.current_num);
add_one.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
current_number += 1;
cur_text.setText(Integer.toString(current_number);
}
});
And similar for the other TextView & onClickListener.
You only set the contents of your TextViews once. You should update them every time you get a click event. Specifically:
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
{
record_number = current_number;
rec_text.setText(String.valueOf(record_number));
}
cur_text.setText(String.valueOf(current_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
}
});
NOTE: if your variables current_number, record_number, cur_text, and rec_text aren't already declared as class member variables, you'll want to do that do that so that they're accessible once you leave the scope of the method you're doing all this in (I assume it's onCreate(...).
What you are going to need to do here is update the labels during the on click events of the button. You currently only update them on activity create. This doesn't execute every time there is a click. Can I answer any questions about the fixed up version below?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final TextView rec_text = (TextView) findViewById(R.id.record_num);
final TextView cur_text = (TextView) findViewById(R.id.current_num);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
record_number = current_number;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}