I have an image called c1.png in drawable-mdpi folder. I want to put it to layout by Java with this:
package ...;
import android.os.Bundle;
//import android.provider.MediaStore.Images;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout)findViewById(getCurrentFocus().getId() );
ImageView img = new ImageView(this);
ViewGroup.LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
img.setLayoutParams(lp);
img.setImageDrawable(getResources().getDrawable(R.drawable.c1));
layout.addView(img);
setContentView(layout);//Doesn't matter, if it's commented or not. The error still exists.
}
#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;
}
}
I got: "Unfortunately, %application_name has stopped" when launched it. I saw many examples, using R.id.* in id params, but it stopped too (like R.id.linearLayout1), or R had not such constansts (like R.id.c1).
How can I do this?
import android.app.Activity;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout)findViewById(R.id.layoutID ); // //layoutID is id of the linearLayout that defined in your main.xml file
ImageView img = new ImageView(this);
ViewGroup.LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
img.setLayoutParams(lp);
img.setBackgroundResource(R.drawable.c1);
layout.addView(img);
}
#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;
}
}
Hope this helps.
You need not do a setContentView(layout); Also, replace :
findViewById(getCurrentFocus().getId() )
by
findViewById(R.id.layoutId); //layoutId is the id of the linearLayout defined in your layout.xml file. And R would refer to your local resources folder path and not the android Resources path.
You xml file could look something like this (this would be the main.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
<LinearLayout
android:id="#+id/layoutId"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Use the code :
ImageView img = new ImageView(this);
img.setImageResource(R.drawable.c1);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I just starting learning to develop an android app and for that i followed google's basic tutorial.
In the tutorial there is simply a textbox and a button. On pressing the button it takes the text from the textbox and displays it in another activity. But somehow the button isn't working for me.
Here is the code for the fragment_main.xml, MainActivity.java and DisplayMessageActivity.java. I just want to know if i am doing something wrong or if i am missing something.
fragmant_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
onClick="sendMessage" />
</LinearLayout>
MainActivity.java:
package com.example.first;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayMessageActivity.java
package com.example.first;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_message, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
return rootView;
}
}
}
EDIT **
In your fragment_main.xml file the the last line of your Button tag should be : android:onClick="sendMessage" instead of onClick="sendMessage"
I created a blank app with just an ad and it force closes when it loads. Heres what i did:
added the google-play-services library to the project
inserted the meta-data tag
inserted the permissions tag
inserted the activity tag
inserted the xmlns line and com.google tag in the fragment xml
imported com.google... into the main java
added the adview code into the main java
saved it.
There are zero errors and the graphical display shows a box that says "ads by google" but doesnt show ads. When i try to run it in an emulator, the app force closes. Did i miss something? Thanks guys!
package com.example.abc;
import com.google.android.gms.ads.*;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdView adView = (AdView)this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
.build();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Ok thanks the link works and I have looked at the code.
I have edited your question to include the code.
Could you try it this way please:
And instead of simply importing import com.google.android.gms.ads.*;
Try using:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adView = new AdView(this); //I couldn't see this line in your code. It goes under the line setContentView(R.layout.activity_main);
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
adView.loadAd(adRequest);
And let me know what happens. Also how do you have the ads setup in your XML?
I'm using the popular SlidingMenu library, and the only thing in it is a listview. So I tried using an array adapter to populate it with an ArrayList that I have, but it gives me a NullPointer Exception. So I had a gut feeling that I should try to set the layout of the activity to the layout with the listview, and sure enough, it worked. but that doesn't solve my problem because I need the listview in the DRAWER. Can someone help?
package josh.hutchins.frcmatchscouter2014;
import java.util.ArrayList;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
BlueAllianceHandler bah = new BlueAllianceHandler("sc");
FileIoHandler fih = new FileIoHandler(/*maybe pass in folder path here?*/);
ArrayList<String> testTeams = new ArrayList<String>();
ListView drawerListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerListView = (ListView) findViewById(R.id.drawerListView);
setupSlidingMenu();
//Toast.makeText(this, bah.pullData(), Toast.LENGTH_LONG).show();
pullTeamData();
}
#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;
}
void setupSlidingMenu(){
SlidingMenu menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.LEFT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setMenu(R.layout.menu);
}
void pullTeamData(){
//JUST FOR TESTING PURPOSES
testTeams.add("2655");
testTeams.add("1533");
testTeams.add("900");
testTeams.add("4451");
testTeams.add("2200");
testTeams.add("3301");
testTeams.add("2059");
testTeams.add("5010");
testTeams.add("1747");
testTeams.add("2641");
testTeams.add("4231");
fih.createTeamRecords(testTeams);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
testTeams );
drawerListView.setAdapter(arrayAdapter);
}
}
Just follow these steps :
1.Extend SlidingFragmentActivity in your MainActivity instead of just Activity.
2.Make two layouts of FrameLayout type in your layout folder, like this
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/menu_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
name layouts as menu_frame, content_frame ,menu_frame will hold the list view that you require and content_frame will hold the content.
3.In your MainActivity , do this.
SlidingMenu menu;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setBehindContentView(R.layout.menu_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.menu_frame, new MenuFragment()).commit();
setContentView(R.layout.content_frame);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, new ShockFeedsFragment()).commit();
ab=getActionBar();
menu = getSlidingMenu();
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffset(200);
menu.setMode(SlidingMenu.LEFT_RIGHT );
}
Now design the layout for your left menu , just simply include a listview in a linear layout and name your layout as left_menu.
Make a fragment named MenuFragment , extend ragment class , in onCreateView Method , setup your menu list view as shown below
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v=inflater.inflate(R.layout.left_menu, container, false);
lv=(ListView)v.findViewById(R.id.menuListView);
iv=(ImageView)v.findViewById(R.id.imageMenuProfile);
tv=(TextView)v.findViewById(R.id.textViewProfileName);
LeftMenuAdapter adap=new LeftMenuAdapter(getActivity(), list);
//lv.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(),R.layout.ledt_en_row,R.id.textList,new String[] {"H","R","S","B","C","W"}));
lv.setAdapter(adap);
lv.setOnItemClickListener(new MenuListListener());
return v;
}
I have implemented the same library , did it this way , working perfectly , hope it does same for you :)... good luck.
I'm trying to build an text view that goes to onClick but its not working they told me to add this code I did it but I'm having a lot of errors in it.
this is my MainActivity.java
package imamalsajadsayings.android.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void runNextTask(){
final View addView = getLayoutInflater().inflate(R.layout.addnewtracker, null);
final TrackerInfo newInfo = new TrackerInfo();
//set up for model selection
TextView modelTextview = (TextView)addView.findViewById(R.id.state1);
modelTextview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#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;
}
}
and is my textview
<TextView
android:id="#+id/state1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Tracker_model"
android:clickable="true"
note : I don't have addnewtracker created
errors :
Description Resource Path Location Type
TrackerInfo cannot be resolved to a type MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 20 Java Problem
addnewtracker cannot be resolved or is not a field MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 19 Java Problem
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new OnClickListener(){}) MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 23 Java Problem
TrackerInfo cannot be resolved to a type MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 20 Java Problem
The method onClick(View) of type new OnClickListener(){} must override or implement a supertype method MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 25 Java Problem
OnClickListener cannot be resolved to a type MainActivity.java /ImamAlsajadsayings/src/imamalsajadsayings/android/com line 23 Java Problem
add to activity:
public void modelTextViewClick(View v) {
//do something on click
}
and to layout:
<TextView android:id="#+id/state1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Tracker_model"
android:clickable="true"
android:onClick="modelTextViewClick"/>
and remove your on click listener.
Change below code to your XML file
<TextView android:id="#+id/state1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Tracker_model"
android:clickable="true"
android:onClick="runNextTask"/>
and just modify your java file as follow.
public void runNextTask(View v){
final View addView = getLayoutInflater().inflate(R.layout.addnewtracker, null);
final TrackerInfo newInfo = new TrackerInfo();
//set up for model selection
TextView modelTextview = (TextView)addView.findViewById(R.id.state1);
modelTextview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
you need to import this package to avoid this error
missing this -> import android.view.View.OnClickListener;
Use below piece of code.
package imamalsajadsayings.android.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void runNextTask(){
final View addView = getLayoutInflater().inflate(R.layout.addnewtracker, null);
final TrackerInfo newInfo = new TrackerInfo();
//set up for model selection
TextView modelTextview = (TextView)addView.findViewById(R.id.state1);
}
#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;
}
public void modelTextViewClick(View view)
{
// here view reference is your text view reference.
// put your on click handler code.
}
}
difference between this code and your code is onclick handler. In xml you have already defined a on click handler which you have to use in activity code. Other way set onclick listener handler foe your widget. Your doing both but either one of them is allowed not both for any widget in android.
You haven't call runNextTask from ur onCreate()
u r inflating a layout but didn't add that layout in any layout of ur activity_main layout using addView method
thats why it didn't work
it should be
package imamalsajadsayings.android.com;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
private LayoutInflater inflater;
private LinearLayout someLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
someLayout = (LinearLayout) findViewById(R.id.some_layout); //layout present in activity_main
inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
runNextTask();
}
public void runNextTask(){
LinearLayout mInflatedLayout = (LinearLayout) inflater.inflate(R.layout.addnewtracker, null);
final TrackerInfo newInfo = new TrackerInfo();
//set up for model selection
TextView modelTextview = (TextView)mInflatedLayout.findViewById(R.id.state1);
someLayout.addView(mInflatedLayout);
modelTextview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#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;
}
}
Assuming u r using LinearLayout in ur activity_main layout
I am trying to extract photos from my drawable folder into an ImageView array and add the views from the array as childs to the linearlayout which is part of the horizontalscrollview.
However when I launch the app, it stops unexpectedly. Would anyone know if there is any problem with my code. Thanks a mil for your help.
package com.example.myfirstapp;
import java.lang.reflect.Field;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.text.Layout;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class NewGallery extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_gallery);
LinearLayout gallery = (LinearLayout) findViewById(R.id.mygallery);
Field[] field = R.drawable.class.getFields();
final int arraylength = field.length;
ImageView[] images = new ImageView[arraylength];
for (int i=0; i<=arraylength; i=i+1)
{
images[i] = new ImageView(getApplicationContext());
images[i].setImageDrawable(getResources().getDrawable(getResources().getIdentifier("icon"+i, "drawable", getPackageName())));
gallery.addView(images[i]);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_new_gallery, menu);
return true;
}
If you are using Eclipse, refer to logcat error messages. I think you got a ClassCastException due to incorrect casting :
LinearLayout gallery = (LinearLayout) findViewById(R.id.mygallery).
Are you sure you are casting the correct view ?